package com.smart.community.region.controller;

import java.util.List;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

import com.smart.community.region.dto.OwnerStatisticsDTO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.smart.community.commons.annotation.ApiLog;
import com.smart.community.commons.enums.ApiLogOperationType;
import com.smart.community.commons.result.PageResult;
import com.smart.community.commons.result.Result;
import com.smart.community.region.dto.OwnerDTO;
import com.smart.community.region.dto.OwnerUpdateDTO;
import com.smart.community.region.dto.OwnerQueryDTO;
import com.smart.community.region.dto.OwnerWithHouseholdDTO;
import com.smart.community.region.dto.OwnerMobileDetailDTO;
import com.smart.community.commons.utils.SecurityUtils;
import com.smart.community.region.service.IOwnerService;
import com.smart.community.region.service.OwnerListService;
import com.smart.community.region.service.OwnerProcessingService;
import com.smart.community.region.vo.OwnerVO;
import com.smart.community.region.vo.OwnerEditVO;
import com.smart.community.region.entity.Owner;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;

/**
 * 业主管理控制器
 * 
 * @author Wu.Liang
 * @since 2025-08-20
 * @version 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/region/owner")
@Tag(name = "业主管理", description = "业主管理相关接口")
@Validated
public class OwnerController {
    
    @Autowired
    private IOwnerService ownerService;
    
    @Autowired
    private OwnerListService ownerListService;
    
    @Autowired
    private OwnerProcessingService ownerProcessingService;
    
    /**
     * 分页查询业主列表
     * 
     * @param queryDTO 查询条件
     * @return 分页结果
     * @throws Exception 统一异常
     */
    @GetMapping("/page")
    @Operation(summary = "分页查询业主列表", description = "根据条件分页查询业主列表")
    public Result<PageResult<OwnerVO>> getOwnerPage(@Valid OwnerQueryDTO queryDTO) throws Exception {
        log.info("分页查询业主列表，查询条件：{}", queryDTO);
        
        IPage<OwnerVO> page = ownerService.getOwnerPage(queryDTO);
        
        PageResult<OwnerVO> result = PageResult.of(
            queryDTO.getCurrent(),
            queryDTO.getSize(),
            page.getTotal(),
            page.getRecords()
        );
        
        log.info("分页查询业主列表成功，总记录数：{}", page.getTotal());
        return Result.success("查询成功", result);
    }
    
    /**
     * 根据ID查询业主详情
     * 
     * @param id 业主ID
     * @return 业主详情
     * @throws Exception 统一异常
     */
    @GetMapping("/{id}")
    @Operation(summary = "根据ID查询业主详情", description = "根据业主ID查询业主详细信息")
    public Result<OwnerVO> getOwnerById(
            @Parameter(description = "业主ID") @PathVariable @NotNull(message = "业主ID不能为空") Long id) throws Exception {
        log.info("根据ID查询业主详情，业主ID：{}", id);
        
        OwnerVO ownerVO = ownerService.getOwnerById(id);
        
        log.info("根据ID查询业主详情成功，业主ID：{}", id);
        return Result.success("查询成功", ownerVO);
    }
    
    /**
     * 获取当前用户的业主信息
     * 
     * @return 当前用户业主信息
     * @throws Exception 统一异常
     */
    @GetMapping("/current-user")
    @Operation(summary = "获取当前用户业主信息", description = "获取当前登录用户的业主信息")
    public Result<OwnerMobileDetailDTO> getCurrentUserOwnerInfo() throws Exception {
        log.info("获取当前用户业主信息");
        
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            log.warn("用户未登录，无法获取业主信息");
            return Result.error("用户未登录");
        }
        
        // 根据用户ID查询业主信息
        com.smart.community.region.entity.Owner owner = ownerService.getOwnerByUserId(currentUserId);
        if (owner == null) {
            log.info("当前用户未关联业主信息，用户ID：{}", currentUserId);
            return Result.success("查询成功", null);
        }
        
        // 获取移动端业主详情
        OwnerMobileDetailDTO ownerDetail = ownerService.getOwnerMobileDetailById(owner.getId());
        
        log.info("获取当前用户业主信息成功，用户ID：{}，业主ID：{}", currentUserId, owner.getId());
        return Result.success("查询成功", ownerDetail);
    }
    
    /**
     * 根据业主ID获取移动端业主详情（包含关联房户信息）
     * 
     * @param id 业主ID
     * @return 移动端业主详情
     * @throws Exception 统一异常
     */
    @GetMapping("/mobile/{id}")
    @Operation(summary = "获取移动端业主详情", description = "根据业主ID获取移动端专用的业主详情信息，包含关联房户信息")
    public Result<OwnerMobileDetailDTO> getOwnerMobileDetailById(
            @Parameter(description = "业主ID") @PathVariable @NotNull(message = "业主ID不能为空") Long id) throws Exception {
        log.info("获取移动端业主详情，业主ID：{}", id);
        
        OwnerMobileDetailDTO ownerDetail = ownerService.getOwnerMobileDetailById(id);
        
        log.info("获取移动端业主详情成功，业主ID：{}", id);
        return Result.success("查询成功", ownerDetail);
    }
    
    /**
     * 保存业主信息（移动端专用）
     * 
     * @param dto 业主信息
     * @return 保存结果
     * @throws Exception 统一异常
     */
    @PostMapping("/mobile/save")
    @Operation(summary = "保存业主信息", description = "保存或更新业主信息（移动端专用）")
    public Result<OwnerMobileDetailDTO> saveOwnerInfo(@Valid @RequestBody OwnerMobileDetailDTO dto) throws Exception {
        log.info("保存业主信息，业主信息：{}", dto);
        
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            log.warn("用户未登录，无法保存业主信息");
            return Result.error("用户未登录");
        }
        
        // 检查是否已存在业主信息
        com.smart.community.region.entity.Owner existingOwner = ownerService.getOwnerByUserId(currentUserId);
        if (existingOwner != null) {
            // 更新现有业主信息
            OwnerDTO ownerDTO = convertToOwnerDTO(dto);
            ownerService.updateOwner(existingOwner.getId(), ownerDTO);
            log.info("更新业主信息成功，业主ID：{}", existingOwner.getId());
            
            // 返回更新后的业主详情
            OwnerMobileDetailDTO updatedDetail = ownerService.getOwnerMobileDetailById(existingOwner.getId());
            return Result.success("更新成功", updatedDetail);
        } else {
            // 创建新业主信息
            OwnerDTO ownerDTO = convertToOwnerDTO(dto);
            Long ownerId = ownerService.createOwner(ownerDTO);
            log.info("创建业主信息成功，业主ID：{}", ownerId);
            
            // 返回新创建的业主详情
            OwnerMobileDetailDTO newDetail = ownerService.getOwnerMobileDetailById(ownerId);
            return Result.success("创建成功", newDetail);
        }
    }
    
    /**
     * 将OwnerMobileDetailDTO转换为OwnerDTO
     * 
     * @param mobileDetailDTO 移动端业主详情DTO
     * @return 业主DTO
     */
    private OwnerDTO convertToOwnerDTO(OwnerMobileDetailDTO mobileDetailDTO) {
        if (mobileDetailDTO == null) {
            return null;
        }
        
        OwnerDTO ownerDTO = new OwnerDTO();
        ownerDTO.setOwnerName(mobileDetailDTO.getOwnerName());
        ownerDTO.setIdCard(mobileDetailDTO.getIdCard());
        ownerDTO.setPhone(mobileDetailDTO.getPhone());
        ownerDTO.setEmail(mobileDetailDTO.getEmail());
        ownerDTO.setGender(mobileDetailDTO.getGender());
        ownerDTO.setBirthDate(mobileDetailDTO.getBirthDate());
        ownerDTO.setAddress(mobileDetailDTO.getAddress());
        ownerDTO.setOccupation(mobileDetailDTO.getOccupation());
        ownerDTO.setCompany(mobileDetailDTO.getCompany());
        ownerDTO.setEmergencyContact(mobileDetailDTO.getEmergencyContact());
        ownerDTO.setEmergencyPhone(mobileDetailDTO.getEmergencyPhone());
        ownerDTO.setRemark(mobileDetailDTO.getRemark());
        
        return ownerDTO;
    }
    
    /**
     * 创建业主
     * 
     * @param dto 业主信息
     * @return 业主ID
     * @throws Exception 统一异常
     */
    @ApiLog(
        logTitle = "创建业主",
        logType = 2,
        moduleName = "区域管理",
        operationType = ApiLogOperationType.ADD
    )
    @PostMapping
    @Operation(summary = "创建业主", description = "创建新的业主信息")
    public Result<Long> createOwner(@Valid @RequestBody OwnerDTO dto) throws Exception {
        log.info("创建业主，业主信息：{}", dto);
        
        // 使用OwnerProcessingService处理业主信息（新增或更新）
        Owner owner = ownerProcessingService.processOwnerInfo(dto);
        
        log.info("创建业主成功，业主ID：{}", owner.getId());
        return Result.success("创建成功", owner.getId());
    }
    
    /**
     * 更新业主信息
     * 
     * @param id 业主ID
     * @param dto 业主信息
     * @return 更新结果
     * @throws Exception 统一异常
     */
    @ApiLog(
        logTitle = "更新业主信息",
        logType = 2,
        moduleName = "区域管理",
        operationType = ApiLogOperationType.UPDATE
    )
    @PutMapping("/{id}")
    @Operation(summary = "更新业主信息", description = "根据业主ID更新业主信息")
    public Result<Void> updateOwner(
            @Parameter(description = "业主ID") @PathVariable @NotNull(message = "业主ID不能为空") Long id,
            @Valid @RequestBody OwnerUpdateDTO dto) throws Exception {
        log.info("更新业主信息，业主ID：{}，业主信息：{}", id, dto);
        
        ownerService.updateOwner(id, dto);
        
        log.info("更新业主信息成功，业主ID：{}", id);
        return Result.success();
    }
    
    /**
     * 删除业主
     * 
     * @param id 业主ID
     * @return 删除结果
     * @throws Exception 统一异常
     */
    @ApiLog(
        logTitle = "删除业主",
        logType = 2,
        moduleName = "区域管理",
        operationType = ApiLogOperationType.DELETE
    )
    @DeleteMapping("/{id}")
    @Operation(summary = "删除业主", description = "根据业主ID删除业主信息")
    public Result<Void> deleteOwner(
            @Parameter(description = "业主ID") @PathVariable @NotNull(message = "业主ID不能为空") Long id) throws Exception {
        log.info("删除业主，业主ID：{}", id);
        
        ownerService.deleteOwner(id);
        
        log.info("删除业主成功，业主ID：{}", id);
        return Result.success();
    }
    
    /**
     * 批量删除业主
     * 
     * @param ids 业主ID列表
     * @return 删除结果
     * @throws Exception 统一异常
     */
    @ApiLog(
        logTitle = "批量删除业主",
        logType = 2,
        moduleName = "区域管理",
        operationType = ApiLogOperationType.DELETE
    )
    @DeleteMapping("/batch")
    @Operation(summary = "批量删除业主", description = "批量删除多个业主信息")
    public Result<Void> batchDeleteOwners(@RequestBody List<Long> ids) throws Exception {
        log.info("批量删除业主，业主ID列表：{}", ids);
        
        ownerService.batchDeleteOwners(ids);
        
        log.info("批量删除业主成功，删除数量：{}", ids.size());
        return Result.success();
    }
    
    /**
     * 检查身份证号是否已存在
     * 
     * @param idCard 身份证号
     * @param excludeId 排除的业主ID
     * @return 检查结果
     * @throws Exception 统一异常
     */
    @GetMapping("/check/idcard")
    @Operation(summary = "检查身份证号是否已存在", description = "检查身份证号是否已被其他业主使用")
    public Result<Boolean> checkIdCardExists(
            @Parameter(description = "身份证号") @RequestParam String idCard,
            @Parameter(description = "排除的业主ID") @RequestParam(required = false) Long excludeId) throws Exception {
        log.info("检查身份证号是否已存在，身份证号：{}，排除业主ID：{}", idCard, excludeId);
        
        boolean exists = ownerService.checkIdCardExists(idCard, excludeId);
        
        log.info("检查身份证号是否已存在完成，结果：{}", exists);
        return Result.success("检查完成", exists);
    }
    
    /**
     * 检查手机号是否已存在
     * 
     * @param phone 手机号
     * @param excludeId 排除的业主ID
     * @return 检查结果
     * @throws Exception 统一异常
     */
    @GetMapping("/check/phone")
    @Operation(summary = "检查手机号是否已存在", description = "检查手机号是否已被其他业主使用")
    public Result<Boolean> checkPhoneExists(
            @Parameter(description = "手机号") @RequestParam String phone,
            @Parameter(description = "排除的业主ID") @RequestParam(required = false) Long excludeId) throws Exception {
        log.info("检查手机号是否已存在，手机号：{}，排除业主ID：{}", phone, excludeId);
        
        boolean exists = ownerService.checkPhoneExists(phone, excludeId);
        
        log.info("检查手机号是否已存在完成，结果：{}", exists);
        return Result.success("检查完成", exists);
    }
    
    /**
     * 获取业主统计信息
     * 
     * @return 统计信息
     * @throws Exception 统一异常
     */
    @GetMapping("/statistics")
    @Operation(summary = "获取业主统计信息", description = "获取业主相关的统计数据")
    public Result<OwnerStatisticsDTO> getOwnerStatistics() throws Exception {
        log.info("获取业主统计信息");
        
        OwnerStatisticsDTO statistics = ownerService.getOwnerStatistics();
        
        log.info("获取业主统计信息成功");
        return Result.success("获取成功", statistics);
    }
    
    /**
     * 新增业主并关联房户（完整流程）
     * 
     * @param dto 业主房户关联信息
     * @return 操作结果
     * @throws Exception 统一异常
     */
    @ApiLog(
        logTitle = "新增业主并关联房户",
        logType = 2,
        moduleName = "区域管理",
        operationType = ApiLogOperationType.ADD
    )
    @PostMapping("/add-with-household")
    @Operation(summary = "新增业主并关联房户", description = "新增业主信息并同时建立房户关联关系")
    public Result<String> addOwnerWithHousehold(@Valid @RequestBody OwnerWithHouseholdDTO dto) throws Exception {
        log.info("新增业主并关联房户，业主信息：{}，房户ID：{}", dto.getOwnerInfo(), dto.getHouseholdId());
        
        ownerProcessingService.addOwnerWithHousehold(dto.getOwnerInfo(), dto.getHouseholdId());
        
        log.info("新增业主并关联房户成功");
        return Result.success("新增业主并关联房户成功");
    }
    
    /**
     * 获取业主列表（包含关联状态）
     * 
     * @param queryDTO 查询条件
     * @return 分页结果
     * @throws Exception 统一异常
     */
    @GetMapping("/list-with-association")
    @Operation(summary = "获取业主列表（包含关联状态）", description = "获取业主列表并显示关联状态信息")
    public Result<PageResult<OwnerVO>> getOwnerListWithAssociation(@Valid OwnerQueryDTO queryDTO) throws Exception {
        log.info("获取业主列表（包含关联状态），查询条件：{}", queryDTO);
        
        IPage<OwnerVO> page = ownerListService.getOwnerListWithAssociation(queryDTO);
        
        PageResult<OwnerVO> result = PageResult.of(
            queryDTO.getCurrent(),
            queryDTO.getSize(),
            page.getTotal(),
            page.getRecords()
        );
        
        log.info("获取业主列表（包含关联状态）成功，总记录数：{}", page.getTotal());
        return Result.success("查询成功", result);
    }
    
    /**
     * 获取未关联房户的业主列表
     * 
     * @param queryDTO 查询条件
     * @return 分页结果
     * @throws Exception 统一异常
     */
    @GetMapping("/unassociated")
    @Operation(summary = "获取未关联房户的业主列表", description = "获取未关联房户的业主列表")
    public Result<PageResult<OwnerVO>> getUnassociatedOwnerList(@Valid OwnerQueryDTO queryDTO) throws Exception {
        log.info("获取未关联房户的业主列表，查询条件：{}", queryDTO);
        
        IPage<OwnerVO> page = ownerListService.getUnassociatedOwnerList(queryDTO);
        
        PageResult<OwnerVO> result = PageResult.of(
            queryDTO.getCurrent(),
            queryDTO.getSize(),
            page.getTotal(),
            page.getRecords()
        );
        
        log.info("获取未关联房户的业主列表成功，总记录数：{}", page.getTotal());
        return Result.success("查询成功", result);
    }
    
    /**
     * 获取已关联房户的业主列表
     * 
     * @param queryDTO 查询条件
     * @return 分页结果
     * @throws Exception 统一异常
     */
    @GetMapping("/associated")
    @Operation(summary = "获取已关联房户的业主列表", description = "获取已关联房户的业主列表")
    public Result<PageResult<OwnerVO>> getAssociatedOwnerList(@Valid OwnerQueryDTO queryDTO) throws Exception {
        log.info("获取已关联房户的业主列表，查询条件：{}", queryDTO);
        
        IPage<OwnerVO> page = ownerListService.getAssociatedOwnerList(queryDTO);
        
        PageResult<OwnerVO> result = PageResult.of(
            queryDTO.getCurrent(),
            queryDTO.getSize(),
            page.getTotal(),
            page.getRecords()
        );
        
        log.info("获取已关联房户的业主列表成功，总记录数：{}", page.getTotal());
        return Result.success("查询成功", result);
    }

    /**
     * 获取业主编辑数据
     * 
     * @param id 业主ID
     * @return 业主编辑数据
     * @throws Exception 统一异常
     */
    @GetMapping("/edit/{id}")
    @Operation(summary = "获取业主编辑数据", description = "根据业主ID获取业主的编辑数据")
    public Result<OwnerEditVO> getOwnerEditData(
            @Parameter(description = "业主ID") @PathVariable @NotNull(message = "业主ID不能为空") Long id) throws Exception {
        log.info("获取业主编辑数据，业主ID：{}", id);
        
        OwnerEditVO ownerEditVO = ownerService.getOwnerEditById(id);
        
        log.info("获取业主编辑数据成功，业主ID：{}", id);
        return Result.success("获取成功", ownerEditVO);
    }
}
